package dai.learn.write;

import dai.learn.write.utils.WriteDataUtils;
import dai.learn.write.utils.WritePOIUtils;
import dai.learn.write.wrapper.XSSFWorkbookWrapper;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author daify
 * @create 2019-03-22 11:32
 **/
public class MultiWrite {
    
    public static void exec(int max,int threadMax) throws Exception {
        XSSFWorkbookWrapper workbookWrapper = new XSSFWorkbookWrapper();
        workbookWrapper.initTitile(WriteDataUtils.getTitle());
        final List <List <String>> values = WriteDataUtils.getValues(max);

        List <List <List <String>>> item = WriteDataUtils.groupData(values, threadMax);
        Executor executor = new ThreadPoolExecutor(threadMax, threadMax,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());

        AtomicInteger integer = new AtomicInteger(0);

        for (int i = 0; i < item.size(); i++) {
            final List <List <String>> lists = item.get(i);
            int finalI = i * item.get(0).size() + 1;
            Runnable runnable = new Runnable() {
                @Override 
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "执行");
                    WritePOIUtils utils = new WritePOIUtils();
                    utils.setWorkbookData(workbookWrapper.getWorkbook(),lists, finalI);
                    integer.addAndGet(1);
                }
            };
            executor.execute(runnable);
        }

        while (integer.get() < threadMax) {
            
        }
        System.out.println("数据执行完毕");
        WritePOIUtils.writeFile(workbookWrapper.getWorkbook());
        System.out.println("执行完毕");
    }
}
